﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Text;
using Microsoft.Practices.Unity;

using Web.SystemConfig.Services;
using DreamBuilder.Common;

namespace Web.UserControls
{
    public partial class ArchiveFilter : System.Web.UI.UserControl
    {
        private string _filterSql;
        /// <summary>
        /// 过滤SQL，不包含where关键字
        /// </summary>
        public string FilterSql
        {
            get
            {
                if (string.IsNullOrEmpty(_filterSql))
                    _filterSql = CreateFilterSql(fieldNameList);
                return _filterSql;
            }
        }

        public string GetMyString(string name)
        {
            return CResManager.GetString("Views/SystemConfig/Auth_Menu", name);
        }

        private const string archiveSourceKeyName = "yyyy_archiveSourceTable";
        private const string archiveFilteredKeyName = "yyyy_archiveFilteredTable";

        [Dependency]
        public ICodeTable CodeTableService
        {
            get;
            set;
        }

        /// <summary>
        /// true取下拉框的text false取下拉框的值
        /// </summary>
        public bool IsTextField
        {
            get;
            set;
        }

        private string LastFilterSql
        {
            get
            {
                object lastFilterSql = ViewState["LastFilterSql"];
                if (lastFilterSql == null)
                {
                    return string.Empty;
                }
                else
                {
                    return ViewState["LastFilterSql"] as string;
                }
            }
            set { ViewState["LastFilterSql"] = value; }
        }

        //提要
        private string TiYao = string.Empty;


        public string CreateFilterSql(List<string> fieldNameList)
        {
            StringBuilder filterBuilder = new StringBuilder();
            filterBuilder.Append("1=1");

            //档号
            if (!string.IsNullOrEmpty(this.txtArchiveCode.Text.Trim()) && fieldNameList.Contains("ARCHIVENUM"))
            {
                if (this.ddlArchiveCode.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat(" AND ARCHIVENUM='{0}'   ", this.txtArchiveCode.Text.Trim());
                else
                    filterBuilder.AppendFormat(" AND ARCHIVENUM LIKE '%{0}%'  ", this.txtArchiveCode.Text.Trim());
            }

            //提要
            if (!string.IsNullOrEmpty(this.txtTiyao.Text.Trim()) && fieldNameList.Contains("TiYao"))
            {
                if (this.ddlArchiveCode.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat(" AND {0}='{1}'   ", TiYao, this.txtArchiveCode.Text.Trim());
                else
                    filterBuilder.AppendFormat(" AND {0} LIKE '%{1}%'  ", TiYao, this.txtArchiveCode.Text.Trim());
            }

            //全宗号
            if (!string.IsNullOrEmpty(this.txtQuanzonghao.Text.Trim()) && fieldNameList.Contains("FULLFONDSNUM"))
            {
                if (this.ddlQuanzonghao.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat("  AND FULLFONDSNUM='{0}'   ", this.txtQuanzonghao.Text.Trim());
                else
                    filterBuilder.AppendFormat("  AND FULLFONDSNUM LIKE '%{0}%'  ", this.txtQuanzonghao.Text.Trim());
            }

            //题名
            if (!string.IsNullOrEmpty(this.txtTM.Text.Trim()) && fieldNameList.Contains("TITLE"))
            {
                if (this.ddlTM.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat("  AND TITLE='{0}'   ", this.txtTM.Text.Trim());
                else
                    filterBuilder.AppendFormat("  AND TITLE LIKE '%{0}%'  ", this.txtTM.Text.Trim());
            }

            //归档单位
            if (!string.IsNullOrEmpty(this.txtOrgName.Text.Trim()) && fieldNameList.Contains("FILEORGID"))
            {
                if (this.ddlOrgName.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat("  AND FILEORGID='{0}'   ", this.txtOrgName.Text.Trim());
                else
                    filterBuilder.AppendFormat("  AND FILEORGID LIKE '%{0}%'  ", this.txtOrgName.Text.Trim());
            }

            //责任者
            if (!string.IsNullOrEmpty(this.txtPublisher.Text.Trim()) && fieldNameList.Contains("PUBLISHER"))
            {
                if (this.ddlPublisher.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat("  AND PUBLISHER='{0}'   ", this.txtPublisher.Text.Trim());
                else
                    filterBuilder.AppendFormat("  AND PUBLISHER LIKE '%{0}%'  ", this.txtPublisher.Text.Trim());
            }

            //密级
            if (this.ddlSecurityValue.SelectedValue != "-1" && fieldNameList.Contains("F_SECURITYTYPE"))
            {
                if (this.ddlSecurity.SelectedValue == "1")//等于
                {
                    if (IsTextField)
                    {
                        filterBuilder.AppendFormat("  AND F_SECURITYTYPE='{0}'   ", this.ddlSecurityValue.SelectedItem.Text);
                    }
                    else
                        filterBuilder.AppendFormat("  AND F_SECURITYTYPE='{0}'   ", this.ddlSecurityValue.SelectedItem.Value);
                }

            }

            //保密期限
            if (this.ddlKeepSecurityTimeValue.SelectedValue != "-1" && fieldNameList.Contains("F_KEEPSECURITYTIME"))
            {
                if (this.ddlKeepSecurityTime.SelectedValue == "1")//等于
                {
                    if (IsTextField)
                    {
                        filterBuilder.AppendFormat("  AND F_KEEPSECURITYTIME='{0}'   ", this.ddlKeepSecurityTimeValue.SelectedItem.Text);
                    }
                    else
                        filterBuilder.AppendFormat("  AND F_KEEPSECURITYTIME='{0}'   ", this.ddlKeepSecurityTimeValue.SelectedItem.Value);
                }

            }

            //保管期限
            if (this.ddlKeepTimeValue.SelectedValue != "-1" && fieldNameList.Contains("F_KEEPTIME"))
            {
                if (this.ddlKeepTime.SelectedValue == "1")//等于 
                {
                    if (IsTextField)
                    {
                        filterBuilder.AppendFormat("  AND F_KEEPTIME='{0}'   ", this.ddlKeepTimeValue.SelectedItem.Text);
                    }
                    else
                    {
                        filterBuilder.AppendFormat("  AND F_KEEPTIME='{0}'   ", this.ddlKeepTimeValue.SelectedItem.Value);
                    }
                }

            }

            //载体类型
            if (this.ddlCarrierTypeValue.SelectedValue != "-1" && fieldNameList.Contains("F_CARRIERTYPE"))
            {
                if (this.ddlCarrierType.SelectedValue == "1")//等于
                {
                    if (IsTextField)
                    {
                        filterBuilder.AppendFormat("  AND F_CARRIERTYPE='{0}'   ", this.ddlCarrierTypeValue.SelectedItem.Text);
                    }
                    else
                        filterBuilder.AppendFormat("  AND F_CARRIERTYPE='{0}'   ", this.ddlCarrierTypeValue.SelectedItem.Value);
                }

            }
            LastFilterSql = filterBuilder.ToString();
            return filterBuilder.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitControls();
                //if (ControlPage_Load != null)
                //{
                //    ControlPage_Load(sender, e);
                //}

                //添加提要
                var archiveType = Request.QueryString["ArchiveType"];
                if (!string.IsNullOrEmpty(archiveType))
                {
                    List<string> newArchiveType = new List<string>() { "101", "102", "7101", "7102" };
                    if (newArchiveType.Contains(archiveType.Trim()))
                    {
                        TiYao = "TiYao";
                    }
                    else
                    {
                        TiYao = "Summary";
                    }
                }
            }
        }

        /// <summary>
        /// 初始化数据项
        /// </summary>
        private void InitControls()
        {

            //保密期限
            DataSet keepSecurityTime = CodeTableService.GetCodeTableDataByType("KeepSecurityTime");
            if (keepSecurityTime != null && keepSecurityTime.Tables.Count > 0)
            {
                this.ddlKeepSecurityTimeValue.DataSource = keepSecurityTime;
                this.ddlKeepSecurityTimeValue.DataTextField = "Code_Desc";
                this.ddlKeepSecurityTimeValue.DataValueField = "CodeTableID";
                this.ddlKeepSecurityTimeValue.DataBind();
                this.ddlKeepSecurityTimeValue.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            //保管期限
            DataSet KeepTime = CodeTableService.GetCodeTableDataByType("KeepTime");
            if (KeepTime != null && KeepTime.Tables.Count > 0)
            {
                this.ddlKeepTimeValue.DataSource = KeepTime;
                this.ddlKeepTimeValue.DataTextField = "Code_Desc";
                this.ddlKeepTimeValue.DataValueField = "CodeTableID";
                this.ddlKeepTimeValue.DataBind();
                this.ddlKeepTimeValue.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            DataSet CarrierType = CodeTableService.GetCodeTableDataByType("CarrierType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlCarrierTypeValue.DataSource = CarrierType;
                this.ddlCarrierTypeValue.DataTextField = "Code_Desc";
                this.ddlCarrierTypeValue.DataValueField = "CodeTableID";
                this.ddlCarrierTypeValue.DataBind();
                this.ddlCarrierTypeValue.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            DataSet SecurityData = CodeTableService.GetCodeTableDataByType("SecurityType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlSecurityValue.DataSource = SecurityData;
                this.ddlSecurityValue.DataTextField = "Code_Desc";
                this.ddlSecurityValue.DataValueField = "CodeTableID";
                this.ddlSecurityValue.DataBind();
                this.ddlSecurityValue.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
        }

        /// <summary>
        /// 待过滤的档案表-传入
        /// </summary>
        public DataTable ArchiveSourceTable
        {
            get
            {
                return ViewState[archiveSourceKeyName] as DataTable;
            }
            set
            {
                DataTable _archiceSourceTable = value;
                ViewState[archiveSourceKeyName] = value;
                ViewState[archiveFilteredKeyName] = value;
                foreach (DataColumn col in _archiceSourceTable.Columns)
                {
                    fieldNameList.Add(col.ColumnName.ToUpper());
                }
            }
        }

        /// <summary>
        /// 存储待过滤表的列名
        /// </summary>
        private static List<string> fieldNameList = new List<string>();


        /// <summary>
        /// 过滤后的档案表-传出
        /// </summary>
        public DataTable ArchiveFilteredTable
        {
            get
            {
                return ViewState[archiveFilteredKeyName] as DataTable;
            }
        }

        /// <summary>
        /// 过滤
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            Filter();
            //回调函数
            if (AfterFiltered != null)
                AfterFiltered(sender, e);
        }

        public void Filter(bool useLastFilterSql = false)
        {
            DataTable _archiceSourceTable = ViewState[archiveSourceKeyName] as DataTable;
            if (_archiceSourceTable != null && _archiceSourceTable.Rows.Count > 0)
            {
                DataTable _archiveFilteredTable = null;
                //构建过滤器
                string filterSql = string.Empty;
                if (useLastFilterSql)
                {
                    filterSql = LastFilterSql;
                }
                else
                {
                    filterSql = CreateFilterSql(fieldNameList);
                }
                if (string.IsNullOrEmpty(filterSql))
                {
                    _archiveFilteredTable = _archiceSourceTable;
                }
                else
                {
                    //过滤 _archiceSourceTable，并为 _archiveFilteredTable 赋值
                    DataRow[] rows = _archiceSourceTable.Select(filterSql);
                    _archiveFilteredTable = _archiceSourceTable.Clone();
                    foreach (DataRow row in rows)
                    {
                        _archiveFilteredTable.Rows.Add(row.ItemArray);
                    }
                }
                ViewState[archiveFilteredKeyName] = _archiveFilteredTable;
            }
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            this.txtArchiveCode.Text = string.Empty;
            this.txtQuanzonghao.Text = string.Empty;
            this.txtTM.Text = string.Empty;
            this.txtOrgName.Text = string.Empty;
            this.txtPublisher.Text = string.Empty;
            ViewState[archiveFilteredKeyName] = null;
            _filterSql = string.Empty;
            if (ClearFiltered != null)
                ClearFiltered(sender, e);
        }

        /// <summary>
        /// 过滤完成之后触发的事件-通常用于过滤结果的绑定
        /// </summary>
        public event EventHandler AfterFiltered;

        /// <summary>
        /// 点击清除按钮
        /// </summary>
        public event EventHandler ClearFiltered;

        public event EventHandler ControlPage_Load;

        public void SetControlState(Dictionary<string, string> controlState)
        {
            if (controlState.ContainsKey("Title"))
            {
                this.txtTM.Text = controlState["Title"];
            }
            if (controlState.ContainsKey("ArchiveCode"))
            {
                this.txtArchiveCode.Text = controlState["ArchiveCode"];
            }
            if (controlState.ContainsKey("Quanzonghao"))
            {
                this.txtQuanzonghao.Text = controlState["Quanzonghao"];
            }
            if (controlState.ContainsKey("OrgName"))
            {
                this.txtOrgName.Text = controlState["OrgName"];
            }
            if (controlState.ContainsKey("Publisher"))
            {
                this.txtPublisher.Text = controlState["Publisher"];
            }
            if (controlState.ContainsKey("SecurityValue"))
            {
                this.ddlSecurityValue.SelectedIndex = int.Parse(controlState["SecurityValue"]);
            }
            if (controlState.ContainsKey("KeepSecurityTimeValue"))
            {
                this.ddlKeepSecurityTimeValue.SelectedIndex = int.Parse(controlState["KeepSecurityTimeValue"]);
            }
            if (controlState.ContainsKey("KeepTimeValue"))
            {
                this.ddlKeepTimeValue.SelectedIndex = int.Parse(controlState["KeepTimeValue"]);
            }
            if (controlState.ContainsKey("CarrierTypeValue"))
            {
                this.ddlCarrierTypeValue.SelectedIndex = int.Parse(controlState["CarrierTypeValue"]);
            }
        }

        public Dictionary<string, string> GetControlState()
        {
            Dictionary<string, string> controlState = new Dictionary<string, string>();
            controlState["Title"] = this.txtTM.Text;
            controlState["ArchiveCode"] = this.txtArchiveCode.Text;
            controlState["Quanzonghao"] = this.txtQuanzonghao.Text;
            controlState["OrgName"] = this.txtOrgName.Text;
            controlState["Publisher"] = this.txtPublisher.Text;
            controlState["SecurityValue"] = this.ddlSecurityValue.SelectedIndex.ToString();
            controlState["KeepSecurityTimeValue"] = this.ddlKeepSecurityTimeValue.SelectedIndex.ToString();
            controlState["KeepTimeValue"] = this.ddlKeepTimeValue.SelectedIndex.ToString();
            controlState["CarrierTypeValue"] = this.ddlCarrierTypeValue.SelectedIndex.ToString();
            return controlState;
        }
    }
}